/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package company.beans;

import company.globalEvents.CompanyEventDispatcher;
import entities.CompanyOrder;
import facades.CompanyFacade;
import facades.CompanyOrderFacade;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.event.Event;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.Transactional;
import org.primefaces.push.PushContext;
import org.primefaces.push.PushContextFactory;
import qualifiers.EditedEntityEvent;
import qualifiers.PreEditEntityEvent;

/**
 *
 * @author Alvaro
 */
@Named(value = "confirmedPayBean")
@RequestScoped
public class ConfirmedPayBean {

    @Inject
    private CompanyOrderFacade companyOrderFacade;
    @Inject
    private CompanyFacade companyFacade;
    @Inject
    @PreEditEntityEvent
    private Event<CompanyOrder> preEditCompanyOrder;
    @Inject
    @EditedEntityEvent
    private Event<CompanyOrder> editedCompanyOrder;
    private String dsAmount;
    private String dsOrder;
    private String dsReponse;
    private String merchantPassword;
    private String dsMerchantCode;
    private String dsCurrency;
    private String dsSignature;
    private Integer shaLength;
    private Map<String,String> requestParams;
    @Inject
    private CompanyEventDispatcher companyEventDispatcher;
    /**
     * Creates a new instance of ConfirmedPayBean
     */
    public ConfirmedPayBean() {
        merchantPassword="EW257UJW3";
        shaLength=20;
    }

    @Transactional
    @PostConstruct
    public void init(){
      requestParams= FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
      dsAmount = requestParams.get("Ds_Amount");
      dsOrder = requestParams.get("Ds_Order");
      dsMerchantCode = requestParams.get("Ds_MerchantCode");
      dsCurrency = requestParams.get("Ds_Currency");
      dsReponse = requestParams.get("Ds_Response");
      dsReponse = requestParams.get("Ds_Response");
      dsSignature= requestParams.get("Ds_Signature");
       if(dsSignature!= null && dsReponse!= null && dsSignature.equals(createMerchantSignature()) && (dsReponse.equals("0900") || ((Integer.parseInt(dsReponse)>=0)&&(Integer.parseInt(dsReponse)<=99)))){
            CompanyOrder companyOrder = companyOrderFacade.find(new Integer(dsOrder));
            companyOrder.setIsPayed(true);
            companyOrderFacade.edit(companyOrder);
            companyOrder.getCompany().setAvailableCredits(companyOrder.getCompany().getAvailableCredits()+companyOrder.getCompanyProduct().getCredits());
            companyFacade.edit(companyOrder.getCompany());
            companyEventDispatcher.firePaidCompanyProductEvent(companyOrder);
            PushContext pushContext = PushContextFactory.getDefault().getPushContext();
            String channel="/creditsBought/"+companyOrder.getCompany().getIdCompany().toString();
            pushContext.push(channel, companyOrder.getIdCompanyOrder().toString());
       }
    }
    
     private String createMerchantSignature(){
       byte bAmount[]   = new byte[dsAmount.length()];  
       byte bOrder[]    = new byte[dsOrder.length()];  
       byte bCode[]     = new byte[dsMerchantCode.length()];  
       byte bCurrency[] = new byte[dsCurrency.length()];
       byte bResponse[] = new byte[dsReponse.length()];  
       byte bPassword[] = new byte[merchantPassword.length()];   
 
        bAmount   = dsAmount.getBytes();
        bOrder    = dsOrder.getBytes();
        bCode     = dsMerchantCode.getBytes();
        bCurrency = dsCurrency.getBytes();
        bResponse = dsReponse.getBytes();

        bPassword = merchantPassword.getBytes();
        String merchantSignature = new String();
        MessageDigest sha;
        try {
            sha = MessageDigest.getInstance("SHA-1");
            sha.update(bAmount);
            sha.update(bOrder);
            sha.update(bCode); 
            sha.update(bCurrency);
            sha.update(bResponse);
            byte[] hash = sha.digest(bPassword);
            int h = 0;
            String s = new String();
            for(int i = 0; i < shaLength; i++){         
                h = (int) hash[i];          // Convertir de byte a int
                if(h < 0) h += 256;  // Si son valores negativos, pueden haber problemas de conversi¢n.
                s = Integer.toHexString(h); // Devuelve el valor hexadecimal como un String        
                if (s.length() < 2) merchantSignature = merchantSignature.concat("0"); // A¤ade un 0 si es necesario
                    merchantSignature = merchantSignature.concat(s); // A¤ade la conversi¢n a la cadena ya existente
                }
                merchantSignature=merchantSignature.toUpperCase();
            } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(ConfirmedPayBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return merchantSignature;
    }
    
    /**
     * @return the dsOrder
     */
    public String getDsOrder() {
        return dsOrder;
    }

    /**
     * @param dsOrder the dsOrder to set
     */
    public void setDsOrder(String dsOrder) {
        this.dsOrder = dsOrder;
    }

    /**
     * @return the dsReponse
     */
    public String getDsReponse() {
        return dsReponse;
    }

    /**
     * @param dsReponse the dsReponse to set
     */
    public void setDsReponse(String dsReponse) {
        this.dsReponse = dsReponse;
    }

    /**
     * @return the dsAmount
     */
    public String getDsAmount() {
        return dsAmount;
    }

    /**
     * @param dsAmount the dsAmount to set
     */
    public void setDsAmount(String dsAmount) {
        this.dsAmount = dsAmount;
    }

    /**
     * @return the dsMerchantCode
     */
    public String getDsMerchantCode() {
        return dsMerchantCode;
    }

    /**
     * @param dsMerchantCode the dsMerchantCode to set
     */
    public void setDsMerchantCode(String dsMerchantCode) {
        this.dsMerchantCode = dsMerchantCode;
    }

    /**
     * @return the dsCurrency
     */
    public String getDsCurrency() {
        return dsCurrency;
    }

    /**
     * @param dsCurrency the dsCurrency to set
     */
    public void setDsCurrency(String dsCurrency) {
        this.dsCurrency = dsCurrency;
    }

    /**
     * @return the dsSignature
     */
    public String getDsSignature() {
        return dsSignature;
    }

    /**
     * @param dsSignature the dsSignature to set
     */
    public void setDsSignature(String dsSignature) {
        this.dsSignature = dsSignature;
    }

}
